import {
  Breadcrumb,
  Button,
  Card,
  DatePicker,
  Form,
  message,
  Modal,
  Radio,
  Space,
  Table,
  Tag,
} from 'antd';
import { delArticlesAPI, getArticlesAPI } from 'api/articles';
import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import imgSrc from '../../assets/error.png';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import Channel from 'components/Channel';
import { useHistory } from 'react-router-dom';
const { RangePicker } = DatePicker;
export default function ArticleList() {
  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];
  const formDataRef = useRef(null);
  const pageInfoRef = useRef(null);
  const history = useHistory();
  const handleSubmit = (value) => {
    let formData = { ...value };
    // 判断状态是否为-1 是的话删除 不让传-1过去
    if (value.status === -1) {
      // delete 原生删除属性
      delete formData.status;
    }
    // console.log('value  ---  ', value);
    // 判断日期是否存在
    if (value.date) {
      // 更换成需要的日期格式
      const starTime = value.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      const endTime = value.date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss');
      // console.log('starTime  ---  ', starTime);
      formData.begin_pubdate = starTime;
      formData.end_pubdate = endTime;
      // 删除原本的日期格式
      delete formData.date;
      // console.log('formData 53  ---  ', formData);
    }
    // 把数据存入ref
    formDataRef.current = formData;
    getArticlesList(formData);
  };
  // 声明state
  const [articleList, setArticleList] = useState({});
  // 封装文章列表请求
  const getArticlesList = async (params) => {
    const res = await getArticlesAPI(params);
    // console.log('res  ---  ', res.data);
    setArticleList(res.data);
  };
  // 封装切换页码数据函数
  const handleChange = (page, pageSize) => {
    // 将当前页存入ref
    pageInfoRef.current = { page, per_page: pageSize };
    // console.log('formDataRef  ---  ', formDataRef);
    getArticlesList({
      page,
      per_page: pageSize,
      ...(formDataRef.current || {}),
    });
  };
  // 删除按钮
  const handleDelBtn = (id) => {
    Modal.confirm({
      title: '温馨提示',
      content: '你确定要删除吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        // console.log('ok  ---  ');
        // 调用删除接口
        await delArticlesAPI(id);
        const formData = formDataRef.current || {};
        const pageInfo = pageInfoRef.current || {};
        // 重新渲染
        console.log('formDataRef  ---  ', formDataRef);
        getArticlesList({ ...formData, ...pageInfo });
        // 提示用户
        message.success('删除成功');
      },
    });
  };
  useEffect(() => {
    getArticlesList();
  }, []);

  const columns = [
    {
      // 控制表头标题
      title: '图片',
      // 从每行数据的某个字段中取出数据显示在该列
      // 有dataIndex，可以省略key
      dataIndex: 'cover',
      // 指定唯一列
      // key: 'name',
      // render自定义渲染内容
      render: (value) => {
        // console.log('value  ---  ', value);
        // 判断是否有图片
        if (!value.images.length) {
          return <img width={100} height={60} src={imgSrc} alt="" />;
        }
        return <img width={100} height={60} src={value.images[0]} alt="" />;
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (value) => {
        const info = articleStatus.find((item) => item.id === value);
        return <Tag color={info.color}>{info.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      key: 'action',
      render: (value, record, index) => {
        // console.log('value  ---  ', value);
        return (
          <Space>
            <Button
              shape="circle"
              type="primary"
              icon={<EditOutlined />}
              onClick={() => history.push('/edit/' + record.id)}
            ></Button>
            <Button
              onClick={() => handleDelBtn(record.id)}
              danger
              shape="circle"
              icon={<DeleteOutlined />}
            ></Button>
          </Space>
        );
      },
    },
  ];

  return (
    <div style={{ paddingTop: 24 }}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
        bordered={false}
      >
        <Form
          name="basic"
          autoComplete="off"
          onFinish={handleSubmit}
          initialValues={{ status: -1, channel_id: 0 }}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            <Channel style={{ width: 200 }}></Channel>
          </Form.Item>

          <Form.Item label="日期" name="date">
            <RangePicker />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
        <h1>根据筛选条件共查询到{articleList.total_count}条</h1>
        <Table
          // columns控制列显示
          columns={columns}
          //  dataSource控制每行数据
          dataSource={articleList.results}
          rowKey="id"
          pagination={{
            // 分页切换数据
            onChange: handleChange,
            // 设置分页器位置
            position: ['bottomCenter'],
            current: articleList.page,
            pageSize: articleList.per_page,
            total: articleList.total_count,
          }}
        />
      </Card>
    </div>
  );
}
